package com.bugs.factory;

import com.bugs.pojo.SpiderOption;
import com.bugs.processor.BaseProcessor;
import com.bugs.processor.TestProcessor;
import com.bugs.reptile.Job51Parser;
import com.bugs.reptile.LiepinParser;
import com.bugs.reptile.Parser;
import com.model.WorkBug;
import us.codecraft.webmagic.Spider;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class SpiderFactory {
    private static final int THREAD_COUNT = 1;
    private static Map<Long, Spider> spiderMap = new ConcurrentHashMap<>();
    private static Map<Long, AtomicLong> saveDbCountMap = new HashMap<>(6);


    public static void resetSaveDbCount(long workBugId) {
        saveDbCountMap.get(workBugId).set(0);
    }

    public static void addSaveDbCount(long workBugId) {
        saveDbCountMap.get(workBugId).incrementAndGet();
    }


    /**
     * 执行爬虫任务
     * @param workBug
     */
    public synchronized static void actionSpider(WorkBug workBug) {
        if(spiderMap.get(workBug.getId()) != null) {
            Spider spider = spiderMap.get(workBug.getId());
            if(spider.isExitWhenComplete()) {
                spider = createSpider(workBug);
                spiderMap.put(workBug.getId(), spider);
                spider.runAsync();
            }else {
                spiderMap.get(workBug.getId()).start();
            }
        }else {
            Spider spider = createSpider(workBug);
            spiderMap.put(workBug.getId(), spider);
            spider.runAsync();
        }

        if(saveDbCountMap.get(workBug.getId()) != null) {
            resetSaveDbCount(workBug.getId());
        }else {
            saveDbCountMap.put(workBug.getId(), new AtomicLong(0));
        }

    }

    /**
     * 暂停爬虫任务
     * @param workBug
     */
    public synchronized static void suspendSpider(WorkBug workBug) {
        Spider spider = spiderMap.get(workBug.getId());
        if(spider != null) {
            spider.stop();
        }
    }

    /**
     * 关闭爬虫任务
     * @param workBug
     */
    public synchronized static void closeSpider(WorkBug workBug) {
        Spider spider = spiderMap.remove(workBug.getId());
        if(spider != null) {
            spider.stop();
            spider.close();
            resetSaveDbCount(workBug.getId());
        }
    }

    public static boolean workIsActioning(WorkBug workBug) {
        Spider spider = spiderMap.get(workBug.getId());
        if(spider == null) return false;
        return spiderMap.get(workBug.getId()).getThreadAlive() >= 1;
    }

    public static LocalDateTime workStartTime(WorkBug workBug) {
        Spider spider = spiderMap.get(workBug.getId());
        if(spider == null) return null;
        return spider.getStartTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
    }

    public static long getSaveDbCount(WorkBug workBug) {
        AtomicLong count = saveDbCountMap.get(workBug.getId());
        if(count == null) return 0;
        return count.get();
    }


    // 创建爬虫对象
    private static Spider createSpider(WorkBug workBug) {
        Spider spider = null;
        if(workBug.getReptileClass().equals(SpiderOption.JOB51_SPIDER.getType())) {
            spider = Spider.create(new BaseProcessor(new Job51Parser(), workBug));
        }else if(workBug.getReptileClass().equals(SpiderOption.BOSS_SPIDER.getType())) {

        }else if(workBug.getReptileClass().equals(SpiderOption.LIEPIN_SPIDER.getType())) {
            spider = Spider.create(new BaseProcessor(new LiepinParser(), workBug));
        }

        spider.addUrl(workBug.getStartUrl()).thread(THREAD_COUNT);
        return spider;
    }

    public static void main(String[] args){
        WorkBug bug = new WorkBug();
        bug.setStartUrl("https://www.liepin.com/zhaopin/?init=-1&headckid=a618af5408626f25&flushckid=1&fromSearchBtn=2&dqs=050020010&ckid=f616f2976b126b9d&sfrom=click-pc_homepage-centre_searchbox-search_new&key=java+&siTag=v5Qhj_BkoVigcSj2a0QCkw%7E_FrslumzzaHrHe3aSW0VTQ&d_sfrom=search_fp&d_ckId=3a9d1defdedd516089c57076efbfdca1&d_curPage=0&d_pageSize=40&d_headId=33c999fa6b2940ddcb11b5eeff206de4");
        TestProcessor testProcessor = new TestProcessor(new LiepinParser(), bug);
        Spider.create(testProcessor).addUrl(bug.getStartUrl()).thread(THREAD_COUNT).run();
    }


}
